<template>
  <div class="ChangePassword_container add_container">
    <div class="main_main">

      <el-form ref="dataForm" :inline="true" :model="formData" size="mini" :rules="rules">
        <el-form-item label="登录手机号" prop="phone">
          <el-input v-model="phone" disabled />
        </el-form-item>
        <el-form-item v-if="codeStatus" label="验证码" prop="code">

          <div class="login_container_right_main_input2">
            <el-input v-model="formData.code" placeholder="请输入" />
            <a v-if="leftSecond==0" class="login_container_right_main_input2_getCode canClick" @click="sendVerify">发送验证码</a>
            <div v-else class="login_container_right_main_input2_getCode">{{ leftSecond }} 秒后重新发送</div>
          </div>
        </el-form-item>
        <el-form-item v-if="!codeStatus" label="原密码" prop="oldPassword">
          <el-input v-model="formData.oldPassword" type="password" auto-complete="new-password" placeholder="请输入" />
          <!--          <el-input v-model="formData.newPassword" placeholder="请输入" />-->
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="formData.newPassword" type="password" auto-complete="new-password" placeholder="请输入" />
          <!--          <el-input v-model="formData.newPassword" placeholder="请输入" />-->
        </el-form-item>
        <el-form-item label="重复新密码" prop="repeatNewPassword">
          <el-input v-model="formData.repeatNewPassword" type="password" auto-complete="new-password" placeholder="请输入" />
          <!--          <el-input v-model="formData.repeatNewPassword" placeholder="请输入" />-->
        </el-form-item>
      </el-form>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="submitForm()">确定</el-button>
    </div>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { updatePassword } from '@/api/system/user'
import { sendPhoneCode } from '@/api/common/login'
// api方法
export default {
  name: 'ChangePassword',
  props: {
    layerid: {},
    id: {},
    defaultValue: {}
  },
  data() {
    // 自定义表单验证
    const validatePassword = (rule, value, callback) => {
      const reg = /^(?=.*[A-Za-z])(?=.*\d)[^]{8,}$/
      if (!value) {
        callback('新密码不能为空')
      } else if (!reg.test(this.formData.newPassword)) {
        callback('密码限制至少8位，需同时包含数字、字母。')
      } else {
        callback()
      }
    }
    const validateNewPassword = (rule, value, callback) => {
      if (value == '') {
        callback('请再次输入密码')
      } else if (value !== this.formData.newPassword) {
        callback('两次输入密码不一致')
      } else {
        callback()
      }
    }
    return {
      formData: {
        loginPhone: '',
        oldPassword: '',
        newPassword: '',
        repeatNewPassword: ''
      },
      codeStatus: true,
      leftSecond: 0,
      timer: undefined,
      rules: {
        code: [
          { required: true, message: '验证码不能为空', trigger: 'change' }
        ],
        oldPassword: [
          { required: true, message: '原密码不能为空', trigger: 'change' }
        ],
        newPassword: [
          { required: true, validator: validatePassword, trigger: 'change' }
        ],
        repeatNewPassword: [
          { required: true, validator: validateNewPassword, trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'userId', 'userName', 'phone'
    ])
  },
  mounted() {
    this.codeStatus = this.$store.state.user.codeStatus
    console.log(this.$store.state.user.codeStatus)
  },
  methods: {
    sendVerify() {
      if (this.leftSecond !== 0) {
        return
      }

      // if (!this.formData.phone) {
      //   this.$message({
      //     message: '请输入手机号',
      //     type: 'warning'
      //   })
      //   return
      // }
      // const reg = /^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/
      // if (!reg.test(this.formData.phone)) {
      //   this.$message({
      //     message: '请输入正确的手机号',
      //     type: 'warning'
      //   })
      //   return
      // }
      sendPhoneCode({ phone: this.phone }).then(res => {
        if (res) {
          this.startTimer()
        }
      })
    },
    startTimer() { // 开始定时器
      this.leftSecond = 60
      this.timer = setInterval(() => {
        this.leftSecond--
        if (this.leftSecond == 0) {
          this.stopTimer()
        }
      }, 1000)
    },
    stopTimer() { // 关闭定时器
      if (this.timer) {
        clearInterval(this.timer)
      }
    },
    submitForm() {
      const _this = this
      _this.$refs['dataForm'].validate(function(valid) {
        if (valid) { // 表单校验通过
          _this.$confirm('确定要修改密码吗', '修改密码', {// 确认弹框
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            cancelButtonClass: 'cancelClass',
            type: 'warning'
          }).then(() => {
            // const loading = _this.$loading({
            //   target: '.ChangePassword_container',
            //   lock: true,
            //   text: '提交数据中',
            //   spinner: 'el-icon-loading'
            // })
            _this.formData.userId = _this.userId
            const json = {
              newPassword: _this.formData.newPassword,
              oldPassword: _this.formData.oldPassword,
              code: _this.formData.code,
              phone: _this.phone,
              userName: _this.userName
            }
            updatePassword(json).then(res => {
              _this.$message({
                message: res.msg,
                type: 'success'
              })
              _this.$layer.close(_this.layerid)// 关闭弹框

              // 修改密码成功之后，退出登录
              setTimeout(() => {
                _this.logout()
              }, 1500)
            })
            //   .finally(() => {
            //   console.log(111)
            //   loading.close()
            // })
          })
        }
      })
    },
    async logout() {
      await this.$store.dispatch('user/logout')
      this.$router.push(`/login`)
      location.reload()
    },

    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    }
  }
}
</script>
<style lang="less" scoped>
.ChangePassword_container{
  width: 100%;
  height: 100%;
  display: flex;flex-direction: column;justify-content: space-between;

  .login_container_right_main_input2 {
    display: flex;
    align-items: center;
    /deep/ .el-input__inner {
      //border-radius: 8px;background-color: transparent;
    }
    .login_container_right_main_input2_getCode{
      width: 200px;background-color: transparent;
      border-radius: 0px 8px 8px 0px;font-size: 14px;
      display: flex;justify-content: center;align-items: center;
    }
    .canClick{
      color: rgba(57, 125, 255, 1);
    }
    .login_container_right_main_input2_separate{
      height: 20px;
      width: 1px;
      background-color: rgba(206, 206, 206, 1)
    }
  }

  .button_class{
    display: flex;justify-content: flex-end;
  }

  /deep/ .el-form{
    .el-form-item{
      width: 100%;
      display: flex;
      margin-right: 0;
      .el-form-item__label{
        width: 120px !important;
      }
      .el-form-item__content{
        flex: 1;
      }
    }

  }

}
.main_main{
  padding-left: 20px;
  padding-right: 20px;
}
</style>
